package controlSoftware.DataIn;

import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;

import controlSoftware.DataProcess.SensorData;
import controlSoftware.GUI.mainUI;
import controlSoftware.util.RecordHandler;

import de.mud.telnet.*;

/**
 * establishes connection by telnet protocol and parses the retrieved byte
 * stream. SensorData data object is constructed with the retrieved data
 * 
 * @author PaulHuang
 * 
 */
public class TelnetParser {
	public TelnetWrapper telnet = new TelnetWrapper();;
	private String host;
	private int port;
	public final char nlChar = '\n';
	public Queue<String> lineOfData = new LinkedList<String>();
	public RecordHandler recordManager;

	public TelnetParser(String host, int port, RecordHandler recordManager) {
		this.host = host;
		this.port = port;
		this.recordManager = recordManager;
	}

	public TelnetWrapper getTelnetConnection() {
		return telnet;
	}

	/**
	 * establish telnet connection
	 * 
	 * @return
	 */
	public boolean connect() {
		try {
			telnet.connect(host, port);
		} catch (IOException e) {
			e.getMessage();
			return false;
		}
		return true;
	}

	public String getReadings() throws IOException {
		StringBuilder builder = new StringBuilder();
		/*
		 * TODO: need to fine tune the buffer size; smaller buffer size if preferrable; however it may cause more data to be droppped
		 */
		byte[] b = new byte[128];

		telnet.read(b);

		for (int i = 0; i < b.length; i++) {
			if (b[i] != 0) {
				builder.append((char) b[i]);
			}
		}

		String readings = builder.toString();
		return readings;
	}
}